package io.hots.strategy;

import io.hots.enums.BizCodeEnum;
import io.hots.exception.BizException;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import java.util.Collection;

/**
 * @author yueshibin@cetcbigdata.com
 * @date 2022/9/6 3:05 下午
 */
public class CustomTablePreciseShardingAlgorithm implements PreciseShardingAlgorithm<String> {

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<String> shardingValue) {
        //获取表名的最后⼀位，真实配置的表名
        String codeSuffix = shardingValue.getValue();
        codeSuffix = codeSuffix.substring(codeSuffix.length() - 1);

        for (String targetName : availableTargetNames) {
            //获取表名的最后⼀位，真实配置的表名
            String targetNameSuffix = targetName.substring(targetName.length() - 1);
            //如果⼀致则返回
            if (codeSuffix.equals(targetNameSuffix)) {
                return targetName;
            }
        }
        //抛异常
        throw new BizException(BizCodeEnum.DB_ROUTE_NOT_FOUND);
    }

}